const express = require("express");
const router = express.Router();
const passport = require("passport");
const Shop = require("../../../models/Shop");
const auth = passport.authenticate("jwt", { session: false });
const errorHandler = require("../../../middlewares/errorHandler");

// @route  GET api/shop/test
router.get("/test", (req, res) => res.json({ msg: "shop works" }));

// @route  POST api/shop/add
router.post("/add", auth, async (req, res) => {
  try {
    const { category, products } = req.body;
    let shop = await Shop.findOne({ category });

    if (shop) {
      shop.products.push(...products);
      await shop.save();
      console.log("成功添加数据到已存在的分类:", shop);
      return res.status(200).json({ success: true, data: shop });
    } else {
      shop = await Shop.create({ category, products });
      console.log("成功创建新的分类并添加数据:", shop);
      return res.status(200).json({ success: true, data: shop });
    }
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/shop
router.get("/", auth, async (req, res) => {
  try {
    const shops = await Shop.find();
    console.log("成功检索商品:", shops);
    res.status(200).json({ success: true, count: shops.length, data: shops });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/shop/:id
router.get("/:id", auth, async (req, res) => {
  try {
    let shop = await Shop.findById(req.params.id);
    if (shop) {
      console.log("成功检索商品类别:", shop);
      return res.status(200).json({ success: true, data: shop });
    }
    const shops = await Shop.find();
    for (const s of shops) {
      const item = s.products.id(req.params.id);
      if (item) {
        console.log("成功检索商品:", item);
        return res.status(200).json({ success: true, data: item });
      }
    }
    console.error("未找到商品");
    return res.status(404).json({ success: false, error: "未找到商品" });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  PUT api/shop/edit
router.put("/edit", auth, async (req, res) => {
  try {
    const { categoryId, products } = req.body;

    if (!categoryId) {
      return res.status(400).json({ success: false, error: "缺少类别ID" });
    }

    let shop = await Shop.findById(categoryId);
    if (!shop) {
      console.error("未找到类别");
      return res.status(404).json({ success: false, error: "未找到类别" });
    }

    // 使用新的产品数组替换现有的产品
    shop.products = products;

    const savedShop = await shop.save();
    console.log("成功编辑类别:", savedShop);
    return res.status(200).json({ success: true, data: savedShop });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  DELETE api/shop/delete
router.delete("/delete", auth, async (req, res) => {
  try {
    const { categoryId, products } = req.body;
    if (!categoryId) {
      return res.status(400).json({ success: false, error: "缺少类别ID" });
    }
    let shop = await Shop.findById(categoryId);
    if (!shop) {
      console.error("未找到类别");
      return res.status(404).json({ success: false, error: "未找到类别" });
    }
    if (products && products.length > 0) {
      // 删除类别中的特定产品
      products.forEach((productId) => {
        shop.products.id(productId).remove();
      });
    } else {
      // 删除整个类别
      await shop.remove();
      console.log("成功删除类别:", categoryId);
      return res
        .status(200)
        .json({ success: true, data: `类别 ${categoryId} 已删除` });
    }
    const savedShop = await shop.save();
    console.log("成功删除类别中的产品:", savedShop);
    return res.status(200).json({ success: true, data: savedShop });
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;
